package org.sump.mysql;

import org.sump.data.Permission;

/**
 * Declares all privildges for MySQL objects (databases, tables, view, procedures, functions).
 * @author Sergey Grigorchuk (sergey.grigorchuk@gmail.com)
 */
public enum MySQLPermission implements Permission {
	SELECT,
	INSERT,
	UPDATE,
	DELETE,
	CREATE,
	DROP,
	GRANT,
	REFERENCES,
	INDEX,
	ALTER,
	CREATE_VIEW("CREATE VIEW", MySQLVersion.VERSION_5XX),
	SHOW_VIEW("SHOW VIEW", MySQLVersion.VERSION_5XX),
	TRIGGER(MySQLVersion.VERSION_5XX),
	CREATE_TMP_TABLE("CREATE TEMPORARY TABLES"),
	LOCK_TABLES("LOCK TABLES"),
	CREATE_ROUTINE("CREATE ROUTINE", MySQLVersion.VERSION_5XX),
	CREATE_USER("CREATE USER", MySQLVersion.VERSION_5XX),
	ALTER_ROUTINE("ALTER ROUTINE", MySQLVersion.VERSION_5XX),
	EXECUTE(MySQLVersion.VERSION_5XX),
	EVENT(MySQLVersion.VERSION_5XX), 
	REPL_SLAVE("REPLICATION SLAVE"),
	REPL_CLIENT("REPLICATION CLIENT"),
	SUPER,
	SHOW_DB("SHOW DATABASES"),
	FILE,
	PROCESS,
	SHUTDOWN,
	RELOAD,
	
	;

	private final String privName;
	private final MySQLVersion supportedVersions[];
	
	MySQLPermission() {
		supportedVersions  = MySQLVersion.values();
		privName = name();
	}

	MySQLPermission(String privName) {
		supportedVersions  = MySQLVersion.values();
		this.privName = privName;
	}

	MySQLPermission(MySQLVersion supportedVersion) {
		supportedVersions = new MySQLVersion[]{supportedVersion};
		privName = name();
	}
	
	MySQLPermission(String privName, MySQLVersion supportedVersion) {
		supportedVersions = new MySQLVersion[]{supportedVersion};
		this.privName = privName;
	}
	
	public String getName() {
		return name();
	}
	
	public boolean supportVersion(MySQLVersion version) {
		for(MySQLVersion v : supportedVersions) {
			if(v == version) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Privilege name
	 * @return privilege name
	 */
	public String getPrivilegeName() {
		return privName;
	}
	
	/**
	 * Finds permission with given privilege name
	 * @param privilegeName privilege name
	 * @return permission with given privilege name
	 */
	public static MySQLPermission convertFromDBToken(String privilegeName) {
		for(MySQLPermission permission : MySQLPermission.values()) {
			if(privilegeName.equalsIgnoreCase(permission.getPrivilegeName())) {
				return permission;
			}
		}
		return null;
	}
}
